package com.linkwechat.wecom.c.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.linkwechat.common.constant.Constants;
import com.linkwechat.common.exception.wecom.WeComException;
import com.linkwechat.common.utils.StringUtils;
import com.linkwechat.wecom.c.service.IWeAppService;
import com.linkwechat.wecom.client.WeAppClient;
import com.linkwechat.wecom.domain.WeApp;
import com.linkwechat.wecom.domain.dto.WeAppDetailDto;
import com.linkwechat.wecom.mapper.WeAppMapper;
import com.linkwechat.wecom.service.IWeAccessTokenService;
import com.linkwechat.wecom.service.IWeDepartmentService;
import com.linkwechat.wecom.service.IWeUserService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * @author oweson
 * @date 2022/2/16 22:29
 */

@Service
@AllArgsConstructor
public class IWeAppServiceImpl extends ServiceImpl<WeAppMapper, WeApp> implements IWeAppService {
    private WeAppClient weAppClient;
    private IWeDepartmentService iWeDepartmentService;
    private IWeUserService iWeUserService;
    private IWeAccessTokenService iWeAccessTokenService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addWeApp(WeApp weApp) {
        if (this.getOne(new LambdaQueryWrapper<WeApp>()
                .eq(WeApp::getAgentId, weApp.getAgentId())
                .eq(WeApp::getDelFlag, Constants.SUCCESS)) != null) {
            throw new WeComException("AgentId已经存在");
        }
        weApp.setCreateTime(new Date());
        if (this.save(weApp)) {
            WeAppDetailDto agentDto = weAppClient.findAgentById(weApp.getAgentId());
            if (agentDto != null) {
                weApp.setAgentName(agentDto.getName());
                weApp.setCreateTime(new Date());
                weApp.setSquareLogoUrl(agentDto.getSquare_logo_url());
                weApp.setDescription(agentDto.getDescription());
                weApp.setAllowPartys(StringUtils.join(agentDto.getAllow_partys().getPartyid(), ","));
                weApp.setAllowUserinfos(StringUtils.join(agentDto.getAllow_userinfos().getUser(), ","));
                this.updateWeApp(weApp);
            }


        }

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateWeApp(WeApp weApp) {
        if (this.updateById(weApp)) {
            weAppClient.updateAgentById(
                    WeAppDetailDto.builder()
                            .agentid(weApp.getAgentId())
                            .logo_mediaid(weApp.getLogoMediaid())
                            .description(weApp.getDescription())
                            .name(weApp.getAgentName())
                            .build(), weApp.getAgentId()
            );

        }

    }
}
